<?php
	/**
	* 函数功能介绍：根据指定条件返回指定字段的公共方法
	* 创建人: 	Zhou Hailong
	* 创建时间: 2014-11-13 09:15
	* 最后修改人：
	* 最后修改时间：
	*/
    function get_field_by_where($table, $fileds='*', $where='1=1'){
        $CI =& get_instance();
        $sql = "SELECT $fileds FROM {$CI->db->dbprefix}{$table} WHERE $where";
        $result = $CI->db->query($sql)->row_array();
        return $result;
    }

    /**
	* 函数功能介绍：返回关注状态
	* 创建人: 	Zhou Hailong
	* 创建时间: 2014-11-13 11:18
	* 最后修改人：
	* 最后修改时间：
	*/
    function focus_status($status){
    	$show_text = '';
    	switch ($status) {
    		case 1:
    			$show_text = '加关注';
    			break;
    		case 2:
    			$show_text = '已关注';
    			break;
			case 3:
				$show_text = '互相关注';
    			break;
    	}
    }

    /**
    * 函数功能介绍：返回字符串字节数
    * 创建人:  Zhou Hailong
    * 创建时间: 2014-11-13 15:57
    * 最后修改人：
    * 最后修改时间：
    */
    function strLength($str){
        return (strlen($str) + mb_strlen($str,'UTF8')) / 2; 
    }
	
	//根据视频评论表的PID获取被回复的那条评论所属用户的昵称
    function get_nick_by_comment_pid($pid, $table_name = 'comment_video'){
        $CI =& get_instance();
        $sql  = "SELECT u.nick, u.id AS uid FROM {$CI->db->dbprefix}$table_name AS cv ";
        $sql .= "LEFT JOIN {$CI->db->dbprefix}user AS u ON(u.id=cv.uid) ";
        $sql .= "WHERE cv.id=$pid";
        $result = $CI->db->query($sql)->row_array();
        return $result;
    }

    function get_device_type(){
        $agent = isset($_SERVER['HTTP_USER_AGENT']) ? strtolower($_SERVER['HTTP_USER_AGENT']) : 'android';
        if(strpos($agent, 'iphone') || strpos($agent, 'ipad')){
            $type = 2;
        }elseif(strpos($agent, 'android')){
            $type = 1;
        }else{
            $type = 3;
        }
        return $type;
    }
	//获取字符串长度，中文按2字节处理
    function str_len($str){
        $length = strlen(preg_replace('/[x00-x7F]/', '', $str));
        if ($length){
            return strlen($str) - $length + intval($length / 3) * 2;
        }else{
            return strlen($str);
        }
    }

    //绑定标题和描述
    function bind_title_content($title, $content){
        $title = '《' . $title . '》' . $content;
        if(str_len($title) > 286){
            $title = mb_strcut($title, 0, 286, 'utf-8') . '...'; 
        }
        return $title;
    }
	
	/* 时间函数 */
	function time_tran($the_time) {
		$now_time = time ();
		$dur = $now_time - $the_time;
		//今天到现在有多少秒
		$now_sec = time () - strtotime(date("Y-m-d 00:00:00",time()));
		switch ($dur) {
			case $dur < 0:
				return '刚刚';
				break;
			case $dur < 60:
				return '刚刚';
				break;
			case $dur < 3600:
				return floor($dur / 60). '分钟前';
				break;
			case $dur < $now_sec:
				return '今天'.date('H:i', $the_time);
				break;
			default :
				if(date('Y',$now_time) == date('Y',$the_time)) {
					return date('m月d日 H:i',$the_time);
				}else {
					return date('Y-m-d H:i', $the_time);
				}
		}
	}
	//判断视频url是否带是远程路径。
    function get_video_http_url($url=0){
        if($url == '') return $url;
        if(strstr($url, 'http://')){
            return $url;
        }else{
            $url = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$url;
            return $url;
        }
    }
	//表情转换
	function get_emoji_by_text($str = '') {
		$CI =& get_instance();
		$CI->config->load('emoji_config');
		$EMOJI_CFG  = $CI->config->item('EMOJI_CFG');
		return str_replace(array_keys($EMOJI_CFG), $EMOJI_CFG, rawurldecode($str));
		
	}
	
	if (!function_exists('show_message')) { 
	    function show_message($target_url, $content="操作成功", $delay_time = 3) {
	        $CI = &get_instance();
            $data = array(
                'target_url' => $target_url,
                'content' => $content,
                'delay_time' => $delay_time
            );
            $CI->smarty->display('show_message.html', $data);
	    }
	}
	
	function get_ip_address(){
		if (getenv("HTTP_CLIENT_IP"))
			$ip = getenv("HTTP_CLIENT_IP");
		else if(getenv("HTTP_X_FORWARDED_FOR"))
			$ip = getenv("HTTP_X_FORWARDED_FOR");
		else if(getenv("REMOTE_ADDR"))
			$ip = getenv("REMOTE_ADDR");
		else $ip = "Unknow";
		return $ip;
	}

	function get_http_url($url=0, $type='VIDEO'){
        if($url == '') return $url;
        if(strstr($url, 'http://')){
            return $url;
        }else{
        	$CI =& get_instance();
            $CI->config->load('qiniu_config');
            $qiniu_config = $CI->config->item('THINK_SDK_QINIU');
            if($type == 'VIDEO'){
                $url = "http://" . $qiniu_config['VIDEO']['DOMAIN_PREFIX'] . '.' . $qiniu_config['VIDEO']['DOMAIN'] . '/' . $url;
            }elseif($type == 'VIMG'){
            	$url = "http://" . $qiniu_config['VIMG']['DOMAIN_PREFIX'] . '.' . $qiniu_config['VIMG']['DOMAIN'] . '/' . $url;
            }
            return $url;
        }
    }

    function get_qiniu_url($url=0){
        if(strstr($url, 'http://') || $url == ''){
            return $url;
        }else{
            $CI =& get_instance();
            $CI->config->load('qiniu_config');
            $qiniu_config = $CI->config->item('THINK_SDK_QINIU');
            $url = 'http://' . $qiniu_config['VIMG']['DOMAIN_PREFIX'] . '.' . $qiniu_config['VIMG']['DOMAIN'] . '/' .$url;
            return $url;
        }
    }
    
    
    function get_share_wexinapi(){
        require_once "third_party/weixin_api/JSSDK.php";
        $jssdk = new JSSDK("wxa35db5cec9d77d9f", "0715917d36561d106110f0e920b0a1a0", APPPATH . 'cache');
        $signPackage = $jssdk->GetSignPackage();
		return $signPackage;
    }
    
    function write_to_db_logs($key='',$content=''){
        $CI =& get_instance();
        $data=array();
        $data['identifier']=$key;
        $data['content']=$content;
        $data['add_time']=time();
        
        return $CI->db->insert('logs', $data);
    }
	
	function write_to_db_logs_ali($key='',$content=''){
        $CI =& get_instance();
        $data=array();
        $data['identifier']=$key;
        $data['content']=$content;
        $data['add_time']=time();
        
        return $CI->db->insert('logs_ali', $data);
    }

    function is_ajax_request()
    {
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
            return true;
        } else {
            return false;
        }
    }

    function getRandChar($length)
{
    $str = null;
    $strPol = "0123456789";
    $max = strlen($strPol) - 1;

    for ($i = 0; $i < $length; $i++) {
        $str .= $strPol[rand(0, $max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
    }

    return $str;
}

/**
 * 发送验证码短信
 * @param  [type] $phone   [description]
 * @param  [type] $content [description]
 * @return [type]          [description]
 */
function send_verify_code_msg($phone, $content)
{
    $SERVER_URL = "https://api.netease.im/sms/sendtemplate.action";
    $APP_SECRET = "9e9bcd454ade";
    $APP_KEY = "226dea55d918dc41248e9a868cd14e12";
    $template_id = "3058376";
    $NONCE = "ABC123456";

    $curTime = time();
    $checkSum = sha1($APP_SECRET . $NONCE . $curTime);
    // print_r($checkSum);

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $SERVER_URL);

    $header[0] = "Content-Type:application/x-www-form-urlencoded;charset=utf-8";
    $header[] = "AppKey:" . $APP_KEY;
    $header[] = "CurTime:" . $curTime;
    $header[] = "CheckSum:" . $checkSum;
    $header[] = "Nonce:" . $NONCE;
    // echo sha1($str);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, "templateid=" . $template_id . "&mobiles=['" . $phone . "']&params=['" . $content . "']");
    ob_start();
    curl_exec($curl);
    // $error    = curl_error($curl);
    // $info    = curl_getinfo($curl);
    // echo "{'status':1,'code':'','msg':'".$info."'}";
    //
    $result = ob_get_contents();
    ob_end_clean();
    curl_close($curl);
    return $result;
}

function getDistance($lat1, $lng1, $lat2, $lng2){   
    $earthRadius = 6367000; //approximate radius of earth in meters   
    $lat1 = ($lat1 * pi() ) / 180;   
    $lng1 = ($lng1 * pi() ) / 180;   
    $lat2 = ($lat2 * pi() ) / 180;   
    $lng2 = ($lng2 * pi() ) / 180;   
    $calcLongitude = $lng2 - $lng1;   
    $calcLatitude = $lat2 - $lat1;   
    $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);   
    $stepTwo = 2 * asin(min(1, sqrt($stepOne)));   
    $calculatedDistance = $earthRadius * $stepTwo;   
    return round($calculatedDistance);   
}

function get_effective_time($uid, $data_id, $data_type){
    $CI =& get_instance();
    $time = time();
    $sql = "SELECT * FROM {$CI->db->dbprefix}o2o_student_item_terms WHERE data_type='{$data_type}' AND data_id = '{$data_id}' AND uid = '{$uid}'";
    $result = $CI->db->query($sql)->row_array();
    if(!$result){
        return 0;
    }else{
        if($result['lose_time'] > $time){
            $day = ceil(($result['lose_time'] - $time) / (3600 * 24));
        }else{
            $day = 0;
        }
        return $day;
    }
}

function check_effective_time($uid, $data_id, $data_type){
    $CI =& get_instance();
    $time = time();
    $sql = "SELECT * FROM {$CI->db->dbprefix}o2o_student_item_terms WHERE data_type='{$data_type}' AND data_id = '{$data_id}' AND uid = '{$uid}'";
    $result = $CI->db->query($sql)->row_array();
    if(!$result){
        return false;
    }else{
        if($result['lose_time'] > $time || $data_type == 2){
            return true;
        }else{
            return false;
        }
    }
}

function get_vip_endtime($uid){
    $CI =& get_instance();
    $sql = "SELECT vip_expire_day FROM {$CI->db->dbprefix}user WHERE id = $uid";
    $result = $CI->db->query($sql)->row_array();
    return $result['vip_expire_day'];
}

function get_live_time($course_id){
    $CI =& get_instance();
    $sql = "SELECT start_time,end_time FROM {$CI->db->dbprefix}course WHERE id = $course_id";
    $result = $CI->db->query($sql)->row_array();
    return $result;
}
function create_rand_str($min_length = 1, $max_length = 8, $type = 'all'){
    $string = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    if($max_length < $min_length) $max_length = $max_length + $min_length;
    $str_length = mt_rand($min_length, $max_length);
    if($type == 'all'){
        $start_rand = 0;
        $end_rand = strlen($string) - 1;
    }elseif($type == 'number'){
        $start_rand = 52;
        $end_rand = strlen($string) - 1;
    }elseif($type == 'abc'){
        $start_rand = 0;
        $end_rand = strlen($string) - 11;
    }else{
        return false;
    }
    $str = '';
    for ($i=0; $i < $str_length; $i++) { 
        $str .= $string[ mt_rand($start_rand, $end_rand) ];
    }
    return $str;
}

function changeTimeType($seconds){
    if ($seconds > 3600){
        $hours = intval($seconds/3600);
        $minutes = $seconds % 3600;
        $time = $hours.":".gmstrftime('%M:%S', $minutes);
    }else{
        $time = gmstrftime('%H:%M:%S', $seconds);
    }
    return $time;
}

function get_topic_subject($topic_subject_id){
    $subject_info = get_field_by_where("tk_accounts_subject", "title", "id='{$topic_subject_id}'");
    echo $subject_info['title'];
}

function check_user_learn_card($uid, $id, $type){
    $CI =& get_instance();
    $today_time = strtotime(date('Y-m-d',time()));
    $sql = "SELECT item.*, card.title, s_card.id AS sid from {$CI->db->dbprefix}o2o_school_learn_card_item AS item ";
    $sql .= "LEFT JOIN {$CI->db->dbprefix}o2o_school_learn_card AS card ON(card.id = item.card_id) ";
    $sql .= "LEFT JOIN {$CI->db->dbprefix}o2o_school_student_learn_card AS s_card ON(s_card.card_id=item.card_id) ";
    $sql .= " WHERE item.content_id='{$id}' AND item.content_type='{$type}' AND s_card.user_id = '{$uid}' AND s_card.end_time > '{$today_time}' GROUP BY item.card_id";
    $result = $CI->db->query($sql)->row_array();
    return $result;
}
?>